import { _decorator, Component, instantiate, Label, Node, Prefab } from 'cc';
import { UIManager } from '../common/UIManager';
import { Hero } from '../entity/Hero';
import { HeroItem } from './HeroItem';
import HeroApi from '../api/HeroApi';
import { EventManager } from '../event/EventManager';
import { PrefabEnum } from '../common/PrefabEnum';
const { ccclass, property } = _decorator;

@ccclass('HeroList')
export class HeroList extends Component {

    public static instance:HeroList

    @property(Label)
    heroNum:Label
    @property(Label)
    sortType:Label
    @property(Node)
    sortLayout:Node
    @property(Node)
    content:Node
    @property(Node)
    stoneBtn:Node
    @property(Node)
    fightBtn:Node
    @property(Node)
    empty:Node
    @property(Prefab)
    heroItem:Prefab

    /**通用升级魂石数量 */
    public chip:number = 0
    public adChip:number = 0

    public heroList:Hero[] = []

    protected onLoad(): void {
        HeroList.instance = this
    }

    start() {
        this.stoneBtn.on(Node.EventType.TOUCH_END, this.onStone, this)
        this.fightBtn.on(Node.EventType.TOUCH_END, this.onFight, this)

        this.getList()
    }

    async getList(){
        await UIManager.instance.showLoading()
        let res = await HeroApi.Execute({op:1})
        UIManager.instance.closeLoading()
        
        this.setData(res.data)
        
    }

    setData(data){
        this.adChip = data.adChip
        this.chip = data.chip
        let items = data.items

        
        this.heroList = Hero.getListInHeroYard(items)
        this.heroList.sort((a, b) => {
            return b.ad - a.ad
        })

        this.content.destroyAllChildren()
        for(let hero of this.heroList){
            let node = instantiate(this.heroItem)
            this.content.addChild(node)

            node.getComponent(HeroItem).setData(hero)
        }

        this.heroNum.string = `(${this.heroList.length})`

        if(this.heroList.length > 0){
            this.empty.active = false
        }
    }

    onStone(){
        UIManager.instance.openUI(PrefabEnum.HeroStone)
    }

    onFight(){
        UIManager.instance.openUI(PrefabEnum.PVPList)
    }
}


